//
//  MyHomePageViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/11.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "MyHomePageViewController.h"
#import "PhotoCollectionViewCell.h"
#import <UIImageView+AFNetworking.h>
#import "PhotoViewModel.h"
#import "PhotoCollectionViewFlowLaout.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "MeViewModel.h"
#import "DangQiViewController.h"
#import <MBProgressHUD.h>
#import "FindViewModel.h"

@interface MyHomePageViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic ,weak) IBOutlet UIImageView *avatarImageView;
@property (nonatomic ,weak) IBOutlet UILabel *nickNameLabel;
@property (nonatomic ,weak) IBOutlet UILabel *genderLabel;
@property (nonatomic ,weak) IBOutlet UILabel *heightLabel;
@property (nonatomic ,weak) IBOutlet UILabel *signLabel;

@property (nonatomic ,strong) NSString *phoneString;

@property (nonatomic ,weak) IBOutlet UIButton *dangqiButton;
@property (nonatomic ,weak) IBOutlet UIButton *phoneButton;
@property (nonatomic ,weak) IBOutlet UIButton *collectionButton;

@property (nonatomic ,weak) IBOutlet UICollectionView *collectView;
@property (nonatomic ,strong) PhotoViewModel *viewModel;

- (IBAction)dismissSelf:(id)sender;


@end

static NSString *reuseIdentify = @"Cell";

@implementation MyHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _avatarImageView.layer.cornerRadius = 15.0f;
    _avatarImageView.layer.masksToBounds = YES;
    
    _dangqiButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    _dangqiButton.layer.borderWidth = .7f;
    
    
    
    
    
    [_dangqiButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
    
    _phoneButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    _phoneButton.layer.borderWidth = .7f;
    [_phoneButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    

    _collectionButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    _collectionButton.layer.borderWidth = .7f;
    [_collectionButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([PhotoCollectionViewCell class]) bundle:nil];
    _collectView.backgroundColor = [UIColor clearColor];
    [_collectView registerNib:nib forCellWithReuseIdentifier:reuseIdentify];
    
     _viewModel = [[PhotoViewModel alloc] init];
    [[RACObserve(_viewModel, hasLoaded) subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        [_collectView reloadData];
    }];
    
    
    @weakify(self);
    [[_phoneButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_phoneString];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [self.view addSubview:callWebview];
        
    }];
    

    if ([_username length] ==0 ) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        
        [_avatarImageView setImageWithURL:[NSURL URLWithString:[userDefaults objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
        _nickNameLabel.text = [userDefaults objectForKey:@"nickname"];
        _heightLabel.text = [userDefaults objectForKey:@"height"];
        _genderLabel.text = [userDefaults objectForKey:@"gender"];
        _signLabel.text = [userDefaults objectForKey:@"sign"];
        _phoneString = [userDefaults objectForKey:@"phone"];
        
        _collectView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectView.backgroundColor = [UIColor clearColor];
        [_collectView registerNib:nib forCellWithReuseIdentifier:reuseIdentify];
        
        
        PhotoCollectionViewFlowLaout *layout = [[PhotoCollectionViewFlowLaout alloc] init];
        
        [_collectView setCollectionViewLayout:layout];
        
        
       
        [_viewModel fetchDatazWithUser:nil];
        
        [[_dangqiButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            @strongify(self);
            DangQiViewController *dangqiVC = [[DangQiViewController alloc] initWithNibName:NSStringFromClass([DangQiViewController class]) bundle:nil];
            [self presentViewController:dangqiVC animated:YES completion:nil];
            
        }];
        
        
        
    }else{
    
        
        [_viewModel fetchDatazWithUser:_username];
        [[MeViewModel getInfoForUser:_username] subscribeNext:^(id x) {
            [_avatarImageView setImageWithURL:[NSURL URLWithString:[x objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
            _nickNameLabel.text = [x objectForKey:@"nickname"];
            _heightLabel.text = [x objectForKey:@"height"];
            _genderLabel.text = [x objectForKey:@"gender"];
            _signLabel.text = [x objectForKey:@"sign"];
            _phoneString = [x objectForKey:@"phone"];

        }];
        [[_dangqiButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            DangQiViewController *dangqiVC = [[DangQiViewController alloc] initWithNibName:NSStringFromClass([DangQiViewController class]) bundle:nil];
            dangqiVC.username = _username;
            [self presentViewController:dangqiVC animated:YES completion:nil];
            
        }];
    }
    
    [[_collectionButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.mode = MBProgressHUDModeText;
        [self.view addSubview:hud];
        if ([_username length] ==0 ) {
            hud.labelText = @"这是你自己啊";
            [hud showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            }];
            return;
        }
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        id token = [userDefaults objectForKey:@"token"];
        if (!token) {
            hud.labelText = @"你还没有登录哦";
            [hud showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            }];
            return;
        }
        
        
        
        
        
        hud.labelText = @"正在收藏";
        [hud show:YES];
        [[FindViewModel collectUser:_username] subscribeNext:^(id x) {
            hud.labelText = @"收藏成功";
            [hud hide:YES afterDelay:1];
        } error:^(NSError *error) {
            hud.labelText = @"发生错误";
            [hud hide:YES afterDelay:1];
        }];
       
    }];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dismissSelf:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_viewModel numberOfRowsInSection:section];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentify forIndexPath:indexPath];
    
    NSDictionary *dic = [_viewModel dictionaryForItemAtIndexPath:indexPath];
    [cell.imageView setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"image"]] placeholderImage:[UIImage imageNamed:@"hlr"]];
    cell.selectedImageView.hidden = YES;
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((collectionView.frame.size.width-20)/3.0,(collectionView.frame.size.width-20)/3.0*1.1);
    
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    
}

@end
